#pragma once

#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/epoll.h>
#include "Log.hpp"
#include "err.hpp"

static const int gnum = 128;

static const int default_epfd = -1;

class Epoll
{
public:
    Epoll()
        : _epfd(default_epfd)
    {
    }

    void creat()
    {
        _epfd = epoll_create(gnum);
        if (_epfd == -1)
        {
            LogMessage(Error, "epoll_create fail");
            exit(EPOLL_CREATE_ERR);
        }
        LogMessage(Debug, "epoll_creat success");
    }

    void AddMoveEvent(int fd, uint32_t event,int op)
    {
        epoll_event events;
        events.data.fd = fd;
        events.events = event;
        int n = epoll_ctl(_epfd, op, fd, &events);
        if (_epfd == -1)
        {
            LogMessage(Error, "epoll_ctl fail");
            exit(EPOLL_CREATE_ERR);
        }
        LogMessage(Debug, "epoll_ctl success");
    }

    void DeleteEvent(int fd)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
        if (_epfd == -1)
        {
            LogMessage(Error, "epoll_ctl fail");
            exit(EPOLL_CREATE_ERR);
        }
        LogMessage(Debug, "epoll_ctl success");
    }

    int wait(epoll_event *events, int MaxEvents, int timeout)
    {
        return epoll_wait(_epfd, events, MaxEvents, timeout);
    }

    int Fd()
    {
        return _epfd;
    }

    void Close()
    {
        if(_epfd != default_epfd) close(_epfd);
    }

    ~Epoll()
    {
    }

private:
    int _epfd;
};